import ffmpeg


def get_frame_iterator_v2(video_path, step=1):
    """使用ffmpeg-python库"""

    # 创建FFmpeg流
    stream = (
        ffmpeg
        .input(video_path,
               **{'rw_timeout': 5000000})  # 超时参数
        .filter('select', f'not(mod(n,{step}))')
        .output('pipe:', format='rawvideo', pix_fmt='rgb24')
        .run_async(pipe_stdout=True, pipe_stderr=True)
    )

    frame_size =1080 * 1920 * 3

    while True:
        try:
            # 非阻塞读取
            frame_data = stream.stdout.read(frame_size)
            if len(frame_data) == 0:
                break  # 流结束

            if len(frame_data) == frame_size:
                frame_array = np.frombuffer(frame_data, dtype=np.uint8)
                frame = frame_array.reshape((self.height, self.width, 3))
                yield frame

        except Exception as e:
            print(f"读取异常: {e}")
            break

    stream.stdout.close()
    stream.wait()